//
//  ByUIMobleLoginVC.m
//  oc_knowledge
//
//  Created by justiOS on 17/1/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIMobleLoginVC.h"
#import "ByTabBarController.h"
// net
#import "ByApiUser.h"
//
#import "ByCacheUser.h"
#import "UILabel+YBAttributeTextTapAction.h"
@interface ByUIMobleLoginVC ()<UITextFieldDelegate>
{
    NSInteger _countdownTime;   // 倒计时剩余时间
}
@property (nonatomic, strong) UITextField *mobleTF;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *getCodeButton;
@property (nonatomic, strong) UIButton *deleButton1;
@property (nonatomic, strong) UIButton *deleButton2;
@end

@implementation ByUIMobleLoginVC
#pragma mark getter

- (UITextField *)mobleTF {
    if (!_mobleTF) {
        _mobleTF = [[UITextField alloc] init];
        _mobleTF.placeholder = @"请输入手机号";
        _mobleTF.font = FONT(14);
        _mobleTF.tintColor = BY_THEME_COLOR;
        _mobleTF.leftViewMode = UITextFieldViewModeAlways;
        _mobleTF.keyboardType = UIKeyboardTypeNumberPad;
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
        leftLabel.font = FONT(14);
        leftLabel.text = @"手机号";
        leftLabel.textAlignment = NSTextAlignmentCenter;
        _mobleTF.leftView = leftLabel;
        _mobleTF.delegate = self;
        [_mobleTF addTarget:self action:@selector(mobleTFChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _mobleTF;
}

- (UITextField *)codeTF {
    if (!_codeTF) {
        _codeTF = [[UITextField alloc] init];
        _codeTF.placeholder = @"请输入验证码";
        _codeTF.tintColor = BY_THEME_COLOR;
        _codeTF.font = FONT(14);
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
        _codeTF.leftViewMode = UITextFieldViewModeAlways;
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
        leftLabel.font = FONT(14);
        leftLabel.textAlignment = NSTextAlignmentCenter;
        leftLabel.text = @"验证码";
        _codeTF.enabled = NO;
        _codeTF.leftView = leftLabel;
        _codeTF.delegate = self;
        [_codeTF addTarget:self action:@selector(mobleTFChange:) forControlEvents:UIControlEventEditingChanged];
        
    }
    return _codeTF;

}


- (UIButton *)getCodeButton {
    if (!_getCodeButton) {
        _getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _getCodeButton.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
        _getCodeButton.alpha = 0.7;
        _getCodeButton.titleLabel.font = FONT(14);
        [_getCodeButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_getCodeButton addTarget:self action:@selector(getCodeAction:) forControlEvents:UIControlEventTouchUpInside];
        _getCodeButton.enabled = NO;
    }
    return _getCodeButton;
}

- (UIButton *)deleButton1 {
    if (!_deleButton1) {
        _deleButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleButton1 setImage:[UIImage imageNamed:@"Register_delete"] forState:UIControlStateNormal];
        [_deleButton1 addTarget:self action:@selector(deleAction1:) forControlEvents:UIControlEventTouchUpInside];
        _deleButton1.hidden = YES;
    }
    return _deleButton1;
}

- (UIButton *)deleButton2 {
    if (!_deleButton2) {
        _deleButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleButton2 setImage:[UIImage imageNamed:@"Register_delete"] forState:UIControlStateNormal];
        [_deleButton2 addTarget:self action:@selector(deleAction2:) forControlEvents:UIControlEventTouchUpInside];
        _deleButton2.hidden = YES;
    }
    return _deleButton2;
}


- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.layer.cornerRadius = 3;
        _loginButton.backgroundColor = rgba(124, 203, 242, 1);
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
        _loginButton.enabled = NO;
    }
    return _loginButton;
}


#pragma mark UI
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled = true;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEmptyAction:)];
    [self.view addGestureRecognizer:tap];
    [self creatViews];
}

- (void)creatViews {
    
    self.mobleTF.frame = CGRectMake(0, 0, SCREEN_WIDTH - 120, 40);
    self.codeTF.frame = CGRectMake(0, 40, SCREEN_WIDTH - 30, 40);
    [self.view addSubview:self.mobleTF];
    [self.view addSubview:self.codeTF];
    
    self.deleButton1.frame = CGRectMake(SCREEN_WIDTH - 120, 10, 20, 20);
    self.deleButton2.frame = CGRectMake(SCREEN_WIDTH - 30, 50, 20, 20);
    [self.view addSubview:self.deleButton1];
    [self.view addSubview:self.deleButton2];
    
    self.getCodeButton.frame = CGRectMake(SCREEN_WIDTH - 90, 7, 80, 26);
    [self.view addSubview:self.getCodeButton];
    
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(10, 40, SCREEN_WIDTH - 10, 0.5)];
    line1.backgroundColor = BY_LINE_COLOR;
    [self.view addSubview:line1];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 0.5)];
    line2.backgroundColor = BY_LINE_COLOR;
    [self.view addSubview:line2];
    
    self.loginButton.frame = CGRectMake(10, line2.bottom + 20, SCREEN_WIDTH - 20, 40);
    [self.view addSubview:self.loginButton];

//    UILabel *delegateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.loginButton.bottom + 10, SCREEN_WIDTH - 50, 20)];
//    NSString *str1 = @"登录即为同意《用户服务协议》";
//    
//    delegateLabel.textColor = [UIColor lightGrayColor];
//    delegateLabel.adjustsFontSizeToFitWidth = YES;
//    delegateLabel.numberOfLines = 0;
//    delegateLabel.enabledTapEffect = NO;
//    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str1];
//    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, str1.length)];
//    [attrStr addAttribute:NSForegroundColorAttributeName value:BY_THEME_COLOR range:NSMakeRange(6, 8)];
//    [delegateLabel setAttributedText:attrStr];
//    [self.view addSubview:delegateLabel];
//    [delegateLabel yb_addAttributeTapActionWithStrings:@[@"《用户服务协议》"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
//        NSLog(@"%@",string);
//        NSString *str = [NSString stringWithFormat:@"https://api.ryzcgf.com/public/web.php/web/copyright"];
//        ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:str];
//        vc.title = @"用户服务协议";
//        [self by_normalPush:vc hasNavi:YES];
//    }];

    
}


#pragma mark 点击事件
- (void)tapEmptyAction:(UITapGestureRecognizer *)tap {
    
    [UIView animateWithDuration:0.4 animations:^{
        [self.codeTF resignFirstResponder];
        [self.mobleTF resignFirstResponder];
    }];
}

- (void)deleAction1:(UIButton *)button {
    self.mobleTF.text = nil;
    button.hidden = YES;
    self.getCodeButton.enabled = NO;
    _getCodeButton.alpha = 0.7;
}

- (void)deleAction2:(UIButton *)button {
    self.codeTF.text = nil;
    button.hidden = YES;
}

// 获取验证码
- (void)getCodeAction:(UIButton *)button {
    
    // 再次获取验证码定时器倒计时30秒
    _countdownTime = 30;
    NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_countdownAction:) userInfo:nil repeats:YES];
    [timer fire];
    
    
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.mobile = self.mobleTF.text;
    model.type = @"5";
    [ByApiUser getCode:model success:^(ByNetBaseResult *result) {
        // 打开验证码tf 的输入
        self.codeTF.enabled = YES;
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}




// 点击登录按钮
- (void)loginAction:(UIButton *)button {
    
    if ([self.mobleTF.text isStringNull]) {
        [ByCoreToolAlert showOnlyText:@"手机号不能为空"];
        return;
    }
    if ([self.codeTF.text isStringNull]) {
        [ByCoreToolAlert showOnlyText:@"请输入验证码"];
        return;
    }
    if (self.mobleTF.text.length != 11) {
        [ByCoreToolAlert showOnlyText:@"手机号输入不正确"];
        return;
    }
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.mobile = self.mobleTF.text;
    model.code = self.codeTF.text;
    [ByCoreToolAlert showLoadind:@"登录中..." hasMasker:YES];
    [ByApiUser loginWithCode:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        ByModelUser *model = (ByModelUser *)result.data;
        // 缓存用户model
        [ByCacheUser setUserInfo:model];
        [self dismissViewControllerAnimated:YES completion:^{
            ByTabBarController *tab = (ByTabBarController *)((AppDelegate *)BY_APPDELEGATE).window.rootViewController;
            tab.selectedIndex = _seletedTag;
        }];

    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}
#pragma mark - 倒计时处理
- (void)_countdownAction:(NSTimer *)timer {
    if (_countdownTime > 0) {
        self.getCodeButton.enabled = NO;
        self.getCodeButton.alpha = 0.7;
        _countdownTime --;
        [self.getCodeButton setTitle:[NSString stringWithFormat:@"%li秒后重试",_countdownTime] forState:UIControlStateNormal];
    }else {
        [self.getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        if (self.mobleTF.text.length == 11) {
            self.getCodeButton.enabled = YES;
            self.getCodeButton.alpha = 1;
        }
        [timer invalidate];
    }
}

#pragma mark tf delegate
// 开始编辑
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == self.mobleTF) {
        if (textField.text.length > 0) {
            self.deleButton1.hidden = NO;
        }else{
            self.deleButton1.hidden = YES;
        }
    }else{
        if (textField.text.length > 0) {
            self.deleButton2.hidden = NO;
        }else{
            self.deleButton2.hidden = YES;
        }
    }
    
}
// 结束编辑
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.mobleTF) {
        self.deleButton1.hidden = YES;
    }else{
        self.deleButton2.hidden = YES;
    }
}
// 编辑时
- (void)mobleTFChange:(UITextField *)textField {
    if (textField == self.mobleTF) {
        if (textField.text.length > 0) {
            self.deleButton1.hidden = NO;
        }else{
            self.deleButton1.hidden = YES;
        }
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
        // 获取验证码按钮的enabled
        if (textField.text.length == 11) {
            self.getCodeButton.enabled = YES;
            _getCodeButton.alpha = 1;
        }else{
            self.getCodeButton.enabled = NO;
            _getCodeButton.alpha = 0.7;
        }
        
        
    }else {
        if (textField.text.length > 0) {
            self.deleButton2.hidden = NO;
            self.loginButton.enabled = YES;
            self.loginButton.backgroundColor = BY_THEME_COLOR;
        }else{
            self.deleButton2.hidden = YES;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
